import logging
import time

import allure
import pytest
from selenium import webdriver


# @pytest.fixture(scope="function")
# def driver():
#     driver = webdriver.Chrome()
#     driver.maximize_window()
#     driver.get("http://novel.hctestedu.com/")
#     yield driver
#     driver.quit()

@pytest.fixture(scope="function")
def driver(request):
    options = webdriver.ChromeOptions()
    options.add_argument("headless")
    driver = webdriver.Chrome(options=options)
    # driver = webdriver.Chrome()
    driver.maximize_window()
    driver.get("http://novel.hctestedu.com/")
    if "login" in request.keywords:
        with allure.step("登录"):
            driver.find_element("link text","登录").click()
            driver.find_element("id","txtUName").send_keys("13381334750")
            driver.find_element("id","txtPassword").send_keys("123456")
            driver.find_element("id","btnLogin").click()
            time.sleep(0.2)
    yield driver
    driver.quit()

@pytest.hookimpl(hookwrapper=True)
def pytest_runtest_makereport(item,call):
    outcome = yield
    report = outcome.get_result()

    if report.when == "call":
        logging.info("----------日志的头部---------")
        logging.info(f"用例ID:{report.nodeid}")
        logging.info(f"测试结果:{report.outcome}")
        logging.info(f"故障标识:{report.longrepr}")
        logging.info(f"异常信息:{call.excinfo}")
        logging.info(f"用例耗时:{report.duration}")
        logging.info("----------日志的尾部----------")

        allure_text =(
            f"用例ID:{report.nodeid}\n"
            f"测试结果:{report.outcome}\n"
            f"故障标识:{report.longrepr}\n"
            f"异常信息:{call.excinfo}\n"
            f"用例耗时:{report.duration}"
        )
        allure.attach(allure_text,name="测试详细信息",attachment_type=allure.attachment_type.TEXT)

    if report.when == "call" and (report.failed or report.passed):
        driver = item.funcargs.get('driver')    #获得浏览器
        if driver:
            if report.failed:
                with allure.step("添加失败截图"):
                    allure.attach(driver.get_screenshot_as_png(), "失败截图", allure.attachment_type.PNG)
            elif report.passed:
                with allure.step("添加成功截图"):
                    allure.attach(driver.get_screenshot_as_png(), "成功截图", allure.attachment_type.PNG)